package File;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LXW
 * Date: 2022-04-04
 * Time: 14:14
 */
public class Demo16 {
    public static void main(String[] args) throws IOException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入你要查找的根目录(绝对路径或相对路径)");
        String s = scanner.nextLine();
        File dir = new File(s);
        if(!dir.isDirectory()) {
            System.out.println("您输入的目录不存在或者不是目录");
            return;
        }
        System.out.println("请输入你要查找的文件名");
        String token = scanner.nextLine();
        List<File> result = new ArrayList<>();
        scan(dir,token,result);
        System.out.println("总共查找到"+result.size()+"个结果，它们分别是");
        for (File file : result) {
            System.out.println("文件路径"+file.getCanonicalPath()+"请问你是否要删除它(y/n)");
            String in = scanner.nextLine();
            if(in.equalsIgnoreCase("Y")) {
                file.delete();
            }
        }
    }
    public static void scan(File dir, String token, List<File> result) {
        File[] files = dir.listFiles();
        if(files == null || files.length == 0) {
            return;
        }
        for (File file : files) {
            if (file.isDirectory()) {
                scan(file,token,result);
            }else if(file.getName().contains(token)) {
                result.add(file);
            }
        }
    }
}
